<?php 
ArrowController::importModel("org.arrowplatform.model.ArrowDataSource");
ArrowController::importModel("org.arrowplatform.controls.common.criteria.IArrowCriteriaUser");  
class ArrowReportChartCtrl extends ArrowTagContainer {
	
	protected $dataSource;
	private $criteria = null;
	private $jsData = false;
	
	public function configure(){
		
		$this->addProperties(array(
			"width" => "100%",
			"height" => 215,
			"title" => false,
			"xAxisField" => null,			
			"style" => "",
			"type" => "bar",
			"xName" => "",
			"debug" => "0",
			"yName" => ""
		));
		$this->addRequiredProperties(array("xAxisField"));
		$this->addStateProperties(array());
		
	}
	
	public function init(){
		$jsData = array( 
			//"criteria" => base64_encode( serialize($this->criteria) ),
			"selectedFn" => $this->getProperty("selectedFn"),
			//"path" => "./server/standardModels/org/arrowplatform/controls/report/resources/lib2/"
		);

		$jsData["title"] = $this->getProperty("title");
		$jsData["type"] = $this->getProperty("type");
		$jsData["width"] = $this->getProperty("width");
		$jsData["height"] = $this->getProperty("height");
		$jsData["xName"] = $this->getProperty("xName");
		$jsData["yName"] = $this->getProperty("yName");
		$jsData["height"] = $this->getProperty("height");
		$jsData["targetId"] = 'ctrl-report-chart'.$this->getGlobalId();
		$jsData["objectId"] = 'ctrl-report-chart-obj'.$this->getGlobalId();
		
		$y = explode( ";",  $this->getProperty("xAxisField"));
		$dataSource = $this->getFirstChild("ArrowCtrlDatasource");
		
		/*$criteria = $dataSource->getCriteria();
		if($criteria){
			foreach($y as $el )
				$criteria->addOrderBy($el);
		}*/
		
		
		$dataS = $dataSource->getData(true);
		//print "<pre>".ArrowOrmMysql::getLastQuery()."</pre>";
		//print_r( $dataS);
		//exit();
		
		$tmp = array();
		if(isset($dataS[0]) && is_array($dataS[0]) && is_array(reset($dataS[0]))){
			foreach($dataS as $key => $row){
				$tmp[$key] = array();
				foreach( $row as $values )
					$tmp[$key] = array_merge($tmp[$key], $values);
			}
			$dataS = $tmp;
		}
		
		
		
		$yValues = array();
		foreach($dataS as $row){
			$str = "";
			foreach($y as $el ) $str.=$row[$el]." ";
			$yValues[] = $str; 
		}
		$yValues = array_unique($yValues);
		
		/*print "<pre>";
		print_r($yValues);
		print "</pre>";*/
		
		
		$jsData["categories"] = $yValues;
		
		
		
			$seriesData = array();
		
		foreach($yValues as $yValue){
			
			foreach($this->getChildren("ArrowReportSerieCtrl") as $serie){
				$field = $serie->getProperty("field");
				$serieName = $serie->getProperty("title");
				$testField = $serie->getProperty("testField");
				$testValue = $serie->getProperty("testValue");
				
				$seriesData[$serieName][$yValue] = 0;
					
					foreach($dataS as $row){
						$res = ""; foreach($y as $el) $res.=$row[$el]." ";
						if( $res == $yValue){
							if($testField && $row[$testField] != $testValue)
								continue;
							//if(!isset($seriesData[$serieName][$yValue])){
								$seriesData[$serieName][$yValue]+= $row[$field];
							//}else{
								//exit($serieName. " ".$yValue ." ".$testValue);
								 
							//}
						}
					}
			
			}
		}
		
		$series = array();
		$i = 0;
		foreach($seriesData as $serieName => $values){
			$series[$i]["name"] = $serieName;
			
			foreach($values as $key=> $row){
				if($jsData["type"] == "pie")
					$series[$i]["data"][] = array($key, $row);//  $data.= "\n\t\t\t<set value='$row' label='{$key}' />";
				else
					$series[$i]["data"][] = $row;
			}
			$i++;
		}
		
		$jsData["series"] = $series;
		
		$this->registerCssFile( "./server/standardModels/org/arrowplatform/controls/report/resources/ArrowReportChartCtrl.css" );
		$this->registerJs( get_class($this), dirname(__FILE__)."/resources/ArrowReportChartCtrl.js", "#ctrl-".$this->getId(), $jsData);
		
		$this->registerJsFile( "./server/standardModels/org/arrowplatform/controls/report/resources/lib/highcharts.src.js" );
		$this->registerJsFile( "./server/standardModels/org/arrowplatform/controls/report/resources/lib/exporting.js" );
		
	}
	
	public function generateBlockStart(){
		$str='<div class="ctrl-report-chart" style="position: relative;width: '.$this->getProperty("width").'px; height: '.$this->getProperty("height").'px;" type="'.$this->getProperty("type").'">';
		//$str.='<div class="ctrl-report-chart-code"><pre>'.htmlentities( $this->generateChartCode()).'</pre></div>';
		//$str.='<div style="position:absolute; width: 220px; height: 20px;z-index:100; background-color: white;">&nbsp;</div>';
		//$str.='<textarea class="ctrl-report-chart-code" style="display: none;">'.$this->generateChartCode().'</textarea>';
		
		$str.='<div id="ctrl-report-chart'.$this->getGlobalId().'">';
		return $str; 
	}
	
	
	public function generateChartCode(){
		$debug = $this->getProperty("debug");
		$type = $this->getProperty("type");
		
		$y = explode( ";",  $this->getProperty("xAxisField"));
		$dataSource = $this->getFirstChild("ArrowCtrlDatasource");
		
		foreach($y as $el )
			$dataSource->getCriteria()->addOrderBy($el);
		
		$dataS = $dataSource->getData(true);
		

		
		$data = "";
		
		
		$tmp = array();
		if(isset($dataS[0]) && is_array($dataS[0])){
			foreach($dataS as $key => $row){
				$tmp[$key] = array();
				foreach( $row as $values )
					$tmp[$key] = array_merge($tmp[$key], $values);
			}
		}
		
		$dataS = $tmp;
		
		if($debug){
			print "<pre>";
			print_r($dataS);
			print "</pre>";
			return;
		}
		

		
		
		
		$yValues = array();
		foreach($dataS as $row){
			$str = "";
			foreach($y as $el ) $str.=$row[$el]." ";
			$yValues[] = $str; 
		}
		$yValues = array_unique($yValues);
		
		if($type != "circle" ){
			$data.= "\n\t\t<categories>";
			foreach( $yValues as $field){
				$data.= "\n\t\t\t<category label='{$field}' />";
			}
			$data.= "\n\t\t</categories>";
		}
		
		$seriesData = array();
		
		foreach($yValues as $yValue){
			
			foreach($this->getChildren("ArrowReportSerieCtrl") as $serie){
				$field = $serie->getProperty("field");
				$serieName = $serie->getProperty("title");
				$testField = $serie->getProperty("testField");
				$testValue = $serie->getProperty("testValue");
				
				$seriesData[$serieName][$yValue] = 0;
					
					foreach($dataS as $row){
						$res = ""; foreach($y as $el) $res.=$row[$el]." ";
						if( $res == $yValue){
							if($testField && $row[$testField] != $testValue)
								continue;
							//if(!isset($seriesData[$serieName][$yValue])){
								$seriesData[$serieName][$yValue]+= $row[$field];
							//}else{
								//exit($serieName. " ".$yValue ." ".$testValue);
								 
							//}
						}
					}
			
			}
		}
		
		
		
		foreach($seriesData as $serieName => $values){
			
			if($type != "circle")
			$data.= "\n\t\t<dataset seriesName='{$serieName}' >";
			foreach($values as $key=> $row){
				$data.= "\n\t\t\t<set value='$row' label='{$key}' />";
			}
			if($type != "circle")
			$data.= "\n\t\t</dataset>";	
			
		}
		
		$add = "showValues='1'";
		if($type == "circle")
			$add = "showPercentValues='1'";
			
		return  "<chart caption='".$this->getProperty("title")."' xAxisName='".$this->getProperty("xName")."' yAxisName='".$this->getProperty("yName")."' {$add} >{$data}\n</chart>";
		
	}
	public function generateBlockEnd(){
		return "</div><div style=\"clear:both;\"></div></div>";
	}
	
	public function setCriteria( $criteria ){
		throw new ArrowException("[ArrowBindCtrl] Set criteria is not possible");
	}
	
	public function getCriteria(){
		if($this->criteria == null){
			$criteriaCont = $this->getFirstChild("ArrowCtrlCriteria");
			$this->criteria = $criteriaCont->getCriteria();
			$req = ArrowRequestContext::getDefault() ;
			if( isset( $req["unit"] ) ) {
				$this->criteria['AuthUser']->addCondition( 'units_flat', $req["unit"], Criteria::C_BIT_AND );
			}
		}
		return $this->criteria;
	}
	

}
?>
